package com.joven.shelltest.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joven.shelltest.common.constant.CommonCons;
import com.joven.shelltest.entity.SignValueModel;
import com.joven.shelltest.service.SignValueService;
import com.joven.shelltest.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author wzj
 * @Date 2023-11-23 08:49
 **/
@Slf4j
@Component
public class SignInterceptor implements HandlerInterceptor {

    private static final String PLATFORM_CODE_URL = "/sign/";

    /**
     * 调用者身份唯一标识
     */
    private static final String ACCESS_KEY = "access-key";
    /**
     * 时间戳
     */
    private static final String TIMESTAMP = "time-stamp";
    /**
     * 签名
     */
    private static final String SIGN = "sign";
    /**
     * 场景id 随机值
     */
    private static final String SCENE = "scene";

    @Autowired
    private SignValueService signValueService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer url = request.getRequestURL();
        log.info("前置SignInterceptor拦截url：{}", url);
        //签名认证
//        if (url.toString().contains(PLATFORM_CODE_URL)) {
            if (!checkSign(request, response)) {
//            return HandlerInterceptor.super.preHandle(request, response, handler);
                return false;
            }
//        }
        return true;
    }

    private boolean checkSign(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf8");
        String ip = getIpAddr(request);
        System.out.println(ip);
        String accessKey = request.getHeader(ACCESS_KEY);
        String timestamp = request.getHeader(TIMESTAMP);
        String scene = request.getHeader(SCENE);
        String sign = request.getHeader(SIGN);
        if (!StringUtils.isNotBlank(accessKey)) {
            response.getWriter().write("accessKey无效");
            return false;
        }
        if (StringUtils.isBlank(sign)) {
            response.getWriter().write("签名无效");
            return false;
        }

        SignValueModel signValue = signValueService.getOne(new LambdaQueryWrapper<SignValueModel>().eq(SignValueModel::getScene, scene));
        if (Objects.isNull(signValue) || !signValue.getAccessKey().equals(accessKey)) {
            response.getWriter().write("accessKey不存在");
            return false;
        }
        //TODO ip校验 白名单可直接跳过校验
//        if (StringUtils.isNotBlank(openApiDetailDO.getBlackList())) {
//            for (String bIp : openApiDetailDO.getBlackList().split(",")) {
//                if (bIp.equals(ip)) {//黑名单
//                    response.getWriter().write(JSON.toJSONString(ResultUtil.fail("拒绝请求")));
//                    return false;
//                }
//            }
//        }
//        if (StringUtils.isNotBlank(openApiDetailDO.getWhiteList())) {
//            boolean flag = false;
//            for (String bIp : openApiDetailDO.getWhiteList().split(",")) {
//                if (bIp.equals(ip)) {//白名单
//                    flag = true;
//                    break;
//                }
//            }
//            if(!flag){
//                response.getWriter().write(JSON.toJSONString(ResultUtil.fail("拒绝请求")));
//                return false;
//            }
//        }

        if (CommonCons.SIGN_EFFECT.equals(signValue.getInvokeStatus())) {
            response.getWriter().write("访问权限已被冻结");
            return false;
        }

        if (!StringUtils.isNotBlank(timestamp)) {
            response.getWriter().write("时间戳无效");
            return false;
        } else if (StringUtils.isNotEmpty(signValue.getTimeOut())) {
            LocalDateTime localDateTime = LocalDateTime.parse(signValue.getTimeOut(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            long time = Long.parseLong(timestamp);
            LocalDateTime localDateTime1 = Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).toLocalDateTime();
            if (localDateTime.isBefore(localDateTime1)) {
                response.getWriter().write("请求已过期");
                return false;
            }
        }

        Map<String, Object> hashMap = new HashMap<>(16);
        //获取url后边拼接的参数
        String queryStrings = request.getQueryString();
        if (queryStrings != null) {
            for (String queryString : queryStrings.split("&")) {
                String[] param = queryString.split("=");
                if (param.length == 2) {
                    hashMap.put(param[0], param[1]);
                }
            }
        }
        hashMap.put(ACCESS_KEY, accessKey);
        hashMap.put(TIMESTAMP, timestamp);
        hashMap.put(SCENE, scene);
        String secretKey = signValue.getSecretKey();

//        BufferedReader reader = request.getReader();
//        StringBuilder stringBuilder = new StringBuilder();
//        String line;
//        while ((line = reader.readLine()) != null) {
//            stringBuilder.append(line);
//        }
//        String body = stringBuilder.toString();
//
//        if (StringUtils.isNotBlank(body)) {
//            Map<String, Object> map = JSONObject.parseObject(body);
//            if (map != null) {
//                hashMap.putAll(map);
//            }
//        }
        if (!SignUtils.signValidate(hashMap, secretKey, sign)) {
            response.getWriter().write("认证失败");
            return false;
        }
        return true;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.isEmpty() || CommonCons.UN_KNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || CommonCons.UN_KNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || CommonCons.UN_KNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (CommonCons.IP_LOCALHOST.equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error(e.getMessage());
                }
                assert inet != null;
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        //"***.***.***.***".length() = 15
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
